<html>

<head>
<title>CS 143 Project 1B</title>
</head>

<h1>SQL Query</h1>
<p>(Version 1.0 4/22/2012 by Edwin Wong)<br />
Type a SQL search query in the following box:<br/>
(Please limit your input to 600 characters. )
</p>

<FORM ACTION="query.php" METHOD="GET">
<TEXTAREA name="textbox" COLS="60" rows="10"></TEXTAREA>
<INPUT TYPE="submit" VALUE="Submit">
</FORM>


<body>
<?php
$db_connection = mysql_connect("localhost", "cs143", "");
$qInput = $_GET["textbox"];
if (!$db_connection)
{
    $errmsg = mysql_error($db_connection);
    print "Connection to mysql server failed: $errmsg <br />";
    exit(1);
}
//now connected, then enter database
mysql_select_db("CS143", $db_connection);

$result = mysql_query($qInput, $db_connection);

//search query error
if (!$result){
    exit(1);
}
$numf = mysql_num_fields($result);
//make table
echo "<br><font size=5><b>Results from MySQL</b></font>";
echo "<table border='1'><tr align='center'>";
//table headers
for($i=0; $i<$numf; $i++)
{
    $header = mysql_fetch_field($result);
    echo "<th>{$header->name}</th>";
}
echo "</tr>\n";

//now get the tuples into the table
while($row = mysql_fetch_row($result))
{
    //output each row onto the table
    echo "<tr align='center'>";
    //loop throw each tuple in the fetched result 
    foreach($row as $tuple)
    {
        if (is_null($tuple))//replace each NULL with the string N/A
            echo "<td>N/A</td>";
        else
            echo "<td>$tuple</td>";
    }
    echo "</tr>\n";
}
mysql_close($db_connection);
?>
</body>
</html>
